package com.ayoka.utils;

import android.content.res.Resources;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;

import com.ayoka.base.AppContext;

import java.io.File;
import java.io.IOException;


/**
 * 录制音频的控制器
 */
public class AudioRecordManager {

    private static final String TAG = "AudioRecordManager";
    private volatile static AudioRecordManager INSTANCE;
    private MediaRecorder mediaRecorder;
    private String audioFileName;
    private RecordStatus recordStatus = RecordStatus.STOP;

    // 语音存储目录
    private File directory;
    // 开始录制的时间
    private long startRecTime;
    // handler
    private Handler handler;

    public enum RecordStatus {
        READY,
        START,
        STOP
    }

    private AudioRecordManager() {
        handler = new Handler();
    }

    private Runnable amplitudeTask = new Runnable() {
        @Override
        public void run() {
            if (audioRecordListener != null) {
                audioRecordListener.onAudioAmplitudeChanged(getMaxAmplitude());
            }
            handler.postDelayed(this, 150L);
        }
    };

    public static AudioRecordManager getInstance() {
        if (INSTANCE == null) {
            synchronized (AudioRecordManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new AudioRecordManager();
                }
            }
        }
        return INSTANCE;
    }

    public void setAudioSaveDirectory(File directory) {
        if (directory.exists()) {
            this.directory = directory;
        } else {
            this.directory = AppContext.getAppCacheDir();
        }
    }

    public void onPrepare(boolean isPrepared) {
        if (isPrepared) {
            recordStatus = RecordStatus.READY;
            audioFileName = createAudioFileName();
        }
    }

    public void startRecord() {
        if (recordStatus == RecordStatus.READY) {
            mediaRecorder = new MediaRecorder();
            try {
                // 设置录音文件的清晰度
                mediaRecorder.setAudioSamplingRate(44100);
                mediaRecorder.setAudioEncodingBitRate(192000);
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
            mediaRecorder.setAudioChannels(1);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mediaRecorder.setOutputFile(audioFileName);
            try {
                mediaRecorder.prepare();
                mediaRecorder.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            startRecTime = SystemClock.elapsedRealtime();
            recordStatus = RecordStatus.START;
            // 设置获取振幅的runnable
            handler.post(amplitudeTask);
            if (audioRecordListener != null) {
                audioRecordListener.onStartRecord();
            }
        }
    }

    public void stopRecord() {
        if (recordStatus == RecordStatus.START) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
            recordStatus = RecordStatus.STOP;
            if (audioRecordListener != null) {
                long duration = SystemClock.elapsedRealtime() - this.startRecTime;
                audioRecordListener.onCompiledRecord(audioFileName, duration);
            }
        }
    }

    public void cancelRecord() {
        if (mediaRecorder != null) {
            try {
                mediaRecorder.setOnErrorListener(null);
                mediaRecorder.setOnInfoListener(null);
                mediaRecorder.setPreviewDisplay(null);
                mediaRecorder.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mediaRecorder.release();
            mediaRecorder = null;
            recordStatus = RecordStatus.STOP;
            if (audioRecordListener != null) {
                audioRecordListener.onCancelRecord();
            }
            if (!TextUtils.isEmpty(audioFileName)) {
                File file = new File(audioFileName);
                if (file.exists()) {
                    file.delete();
                }
            }
        }
    }

    /**
     * 获得录音的音量，范围 0-32767, 归一化到0 ~ 1
     *
     * @return
     */
    public float getMaxAmplitude() {
        if (recordStatus == RecordStatus.START) {
            return mediaRecorder.getMaxAmplitude() * 1.0f / 32768;
        }
        return 0;
    }

    public String createAudioFileName() {
        long time = System.currentTimeMillis();
        File audioFile = new File(directory, time + "tempAudio.mp3");
        return audioFile.getAbsolutePath();
    }

    private IAudioRecordListener audioRecordListener;

    public void setRecordAudioListener(IAudioRecordListener audioRecordListener) {
        this.audioRecordListener = audioRecordListener;
    }

    public interface IAudioRecordListener {

        /**
         * 开始录制
         */
        void onStartRecord();

        /**
         * 结束录制
         */
        void onCompiledRecord(String audioPath, long duration);

        /**
         * 取消录制
         */
        void onCancelRecord();

        /**
         * 分贝改变
         *
         * @param amplitude 振幅
         */
        void onAudioAmplitudeChanged(float amplitude);

    }

}
